import 'package:flutter/services.dart';
import 'package:safetymonitor/app/core/core.dart';

///特殊作业-自定义输入控件
///[title] 标题
///[isRequired] 是否必填
///[onCallBack] 输入回调
///[text] 默认文字
///[hintText] 提示文字
///[isEnabled] 是否可编辑
///[isShowDivider] 是否显示分割线
///[textInputType] 键盘类型
///[reg] RegExp自定义正则
///[suffixText]后缀的单位
/// demo:
/// ``` dart
/// CustomInputPage(
///   textInputType: TextInputType.number,
///   reg: r'^([1-9]|1[0-9]|2[0-3])$',
///   isShowDivider: false,
///   text: '标题',
///   hintText: '提示',
///   onCallBack: (value){},
/// );
/// ```
class CustomInputPage extends StatelessWidget {
  const CustomInputPage({
    required this.title,
    super.key,
    this.isRequired = true,
    this.onCallBack,
    this.text,
    this.hintText,
    this.isEnabled = true,
    this.isShowDivider = true,
    this.textInputType,
    this.controller,
    this.reg = r'^\d*\.?\d*',
    this.titleColor = AppColors.font_color_black,
    this.titleFontWeight,
    this.suffixText,
  });

  final String title;
  final Color titleColor;
  final bool isRequired;
  final Function(String)? onCallBack;
  final String? text;
  final String? hintText;
  final bool isEnabled;
  final bool isShowDivider;
  final TextInputType? textInputType;
  final TextEditingController? controller;
  final String? reg;
  final FontWeight? titleFontWeight;
  final String? suffixText;

  List<TextInputFormatter> getInputFormatters(TextInputType? keyboardType) {
    if (keyboardType == TextInputType.number) {
      return <TextInputFormatter>[
        FilteringTextInputFormatter.allow(RegExp(reg!)), // r'\b([1-23]|[1-2][0-3])\b'
        // 只允许输入数字和小数点
        DecimalFormatter(),
        // 限制只能输入一个小数点
      ];
    } else {
      return <TextInputFormatter>[];
    }
  }

  @override
  Widget build(BuildContext context) {
    final TextEditingController textController = TextEditingController(text: text);
    textController.selection = TextSelection.fromPosition(TextPosition(offset: textController.text.length));
    if (controller != null) {
      controller!.selection = TextSelection.fromPosition(TextPosition(offset: controller!.text.length));
    }
    return Column(
      children: [
        Row(
          children: [
            Visibility(
                visible: isRequired,
                child: Text(
                  '*',
                  style: TextStyle(
                    fontSize: 14.sp,
                    height: 1.2,
                    color: AppColors.meaning_color_danger,
                  ),
                )),
            Text(
              title,
              style: TextStyle(fontSize: 14.sp, height: 1.1, color: titleColor, fontWeight: titleFontWeight),
            ),
            AppGaps.hGap20,
            Expanded(
                child: TextField(
              enabled: isEnabled,
              controller: controller ?? textController,
              textInputAction: TextInputAction.done,
              keyboardType: textInputType,
              inputFormatters: getInputFormatters(textInputType),
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF262F38),
                fontWeight: FontWeight.w400,
              ),
              textAlign: TextAlign.right,
              maxLines: null,
              decoration: InputDecoration(
                hintText: hintText ?? (isEnabled ? '请输入' : '暂无'),
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  color: AppColors.text_grey,
                ),
                border: InputBorder.none,
              ),
              onSubmitted: onCallBack,
              onChanged: controller == null
                  ? (value) {
                      if (onCallBack != null) {
                        onCallBack!(value);
                      }
                    }
                  : null,
            )),
            Visibility(
              visible: suffixText != null,
              child: Container(
                margin: EdgeInsets.only(left: 12.w),
                child: Text(
                  suffixText ?? '',
                  style: TextStyle(
                    fontSize: 14.w,
                    height: 1.2,
                    color: const Color(0xff262F38),
                  ),
                ),
              ),
            )
          ],
        ),
        Visibility(
            visible: isShowDivider,
            child: Divider(
              height: 1.w,
              color: AppColors.bg_color_grey,
            )),
      ],
    );
  }
}

class DecimalFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.startsWith('.')) {
      // 如果新值以小数点开头，则在前面添加一个0
      return TextEditingValue(
        text: '0${newValue.text}',
        selection: TextSelection.collapsed(offset: newValue.selection.end + 1),
      );
    }

    if (newValue.text.contains('.') && oldValue.text.contains('.') && newValue.text.indexOf('.') != oldValue.text.indexOf('.')) {
      // 如果新值和旧值都包含小数点，并且小数点的位置不同，不允许输入小数点
      return oldValue;
    }
    return newValue;
  }
}
